﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using FlashCards.SL.FlashCardCreator.Views;
using FlashCards.SL.FlashCardCreator.DataService;
using FlashCards.SL.FlashCardCreator.ViewModels;
using FlashCards.SL.FlashCardCreator.Events;
using FlashCards.SL.FlashCardCreator.Utils;

namespace FlashCards.SL.FlashCardCreator
{
    public partial class FlashCardsSilverlightApp : Application
    {
        public int? UserID { get; set; }
        public int? FlashcardSetID { get; set; }
        public FlashCards.Dto.User CurrentUser { get; set; }
        public FlashCards.Dto.FlashcardSet FlashcardSet { get; set; }
        public int? GroupId { get; set; }
        public string ApplicationMode { get; set; }

        MainPageViewModel _mainModel;

        public FlashCardsSilverlightApp()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Initialize(e.InitParams);

            var wrapper = new MultiViewWrapper();
            RootVisual = wrapper;

            var serviceEndpoint = string.Empty;

            if (ApplicationMode == "Production")
                serviceEndpoint = "Release_ISilverlightService";
            else if (ApplicationMode == "Development")
                serviceEndpoint = "Debug_ISilverlightService";

            var page = new LoadingPage();
            var pageModel = new LoadingPanelViewModel(serviceEndpoint);
            page.DataContext = pageModel;
            wrapper.MainBorder.Child = page;
        }

        private void Initialize(IDictionary<string, string> initParams)
        {
            if (initParams.ContainsKey("AppMode"))
            {
                ApplicationMode = initParams["AppMode"];
            }

            if (initParams.ContainsKey("UserID"))
            {
                UserID = int.Parse(initParams["UserID"]);
            }
            if (initParams.ContainsKey("SetID"))
            {
                FlashcardSetID = int.Parse(initParams["SetID"]);
            }
            if (initParams.ContainsKey("GroupId") && !string.IsNullOrEmpty(initParams["GroupId"]))
            {
                GroupId = int.Parse(initParams["GroupId"]);
            }

            //pusty slownik
            var dictionary = new Dictionary<string, List<string>>();
            if (!Application.Current.Resources.Contains("AccentsLettersDictionary"))
                Application.Current.Resources.Add("AccentsLettersDictionary", dictionary);
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        public void ApplicationDataLoaded()
        {
            MultiViewWrapper wrapper = RootVisual as MultiViewWrapper;
            var view = new MainPage();

            var serviceEndpoint = string.Empty;

            if (ApplicationMode == "Production")
                serviceEndpoint = "Release_ISilverlightService";
            else if (ApplicationMode == "Development")
                serviceEndpoint = "Debug_ISilverlightService";

            if (FlashcardSet != null)
            {
                if (!string.IsNullOrEmpty(FlashcardSet.Category.Language))
                {
                    var dictionary = new AccentLettersUtils().GetAccentsForLanguage(FlashcardSet.Category.Language);
                    if (Application.Current.Resources.Contains("AccentsLettersDictionary"))
                        Application.Current.Resources.Remove("AccentsLettersDictionary");
                    Application.Current.Resources.Add("AccentsLettersDictionary", dictionary);
                }
                _mainModel = new MainPageViewModel(FlashcardSet, serviceEndpoint);
            }
            else
                _mainModel = new MainPageViewModel(serviceEndpoint);

            _mainModel.OnSaveChanges += HandleMainModel_OnSaveChanges;
            view.DataContext = _mainModel;
            wrapper.MainBorder.Child = view;
        }

        void HandleMainModel_OnSaveChanges(object sender, FlashcardSetEventArgs e)
        {
            if (FlashcardSet == null && e.FlashcardSetId != 0)
            {
                FlashcardSetID = e.FlashcardSetId;
                _mainModel.EditContext.FlashcardSet.Id = FlashcardSetID.Value;
                _mainModel.IsInEditMode = true;
            }
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
